﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using SyndicateDAO.DatabaseObject;
using System.Web.UI.HtmlControls;
using SyndicateBusiness.Classes;

namespace BigLotterySyndicate.Secured.Draws.Controls
{
    public partial class AddLineFromLastDraw : Base
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Visible)
                return;

            if(this.CurrentDraw.type != draw.drawType.LOTTO)
                this.BasePage.Redirect(String.Format("/Secured/Draws/?dId={0}&Tab=2", this.DrawId));

            SetList();
        }

        private void SetList()
        {
            if (Page.IsPostBack)
                return;

            BindList();
        }

        private void BindList()
        {
            draw previousDraw = this.BasePage.BusinessFacade.DrawBL.GetAllBySyndicateId(this.BasePage.LoggedInUser.syndicateId).Where(d => d.id < this.CurrentDraw.id && d.type == this.CurrentDraw.type).OrderByDescending(d => d.drawdate).FirstOrDefault();

            if (previousDraw != null)
            {
                var query = this.BasePage.BusinessFacade.DrawBL.GetLines(previousDraw.id);

                if (query.Count() > 0)
                {
                    this.RepeaterList.DataSource = query;
                    this.RepeaterList.ItemDataBound += new RepeaterItemEventHandler(RepeaterList_ItemDataBound);
                    this.RepeaterList.DataBind();

                    this.MultiViewList.SetActiveView(this.ViewList);
                }
                else
                {
                    this.MultiViewList.SetActiveView(this.ViewEmpty);
                }
            }
            else
            {
                this.MultiViewList.SetActiveView(this.ViewEmpty);
            }
        }

        void RepeaterList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            line l = e.Item.DataItem as line;

            ((System.Web.UI.HtmlControls.HtmlInputCheckBox)e.Item.FindControl("chkAction")).Value = String.Format("lineId_{0}", l.id);

            ((PlaceHolder)e.Item.FindControl("PlaceHolderAction")).Visible = this.DrawOpen;

            // if (this.Lines.Count() > e.Item.ItemIndex + 1)
            //    ((PlaceHolder)e.Item.FindControl("PlaceHolderAction")).Visible = false;



        }

        #region print

        public string PrintResults()
        {
            if (this.DrawFinished)
            {
                List<string> numbers = this.BasePage.BusinessFacade.ResultBL.GetResultString(CurrentDraw.id).Split(',').ToList();

                List<int> a = new List<int>();

                int counter = 1;
                foreach (string item in numbers)
                {
                    if (counter != 7)

                        a.Add(Int32.Parse(item));
                    else
                    {
                        a.Add(Int32.Parse(item) + 100);
                    }
                    counter++;
                }

                a.Sort();


                StringBuilder builder = new StringBuilder();

                foreach (int n in a)
                {
                    if (n < 100)
                        builder.AppendFormat("<div class=\"no-match\">{0}</div>", n);
                    else
                        builder.AppendFormat("<div class=\"bonus-match\">{0}</div>", n - 100);
                }
                builder.Append("</div>");

                return builder.ToString();

            }
            else
            {
                return "No results yet, please be patient.";
            }



        }

        public string PrintNumbers(Object data)
        {
            line l = data as line;

            List<string> numbers = l.numbers.Split(',').ToList();

            List<int> a = new List<int>();

            foreach (string item in numbers)
            {
                a.Add(Int32.Parse(item));
            }


            a.Sort();
            /*
            if (CurrentDraw.status == draw.drawstatus.FINISHED)
            {
                int totalMatch = 0;
                bool bonusMatch = false;

                StringBuilder builder = new StringBuilder();

                builder.Append("<div class=\"numbers\">");
                foreach (int n in a)
                {
                    /*
                    if (this.Result.Contains(n))
                    {
                        builder.AppendFormat("<div class=\"match\">{0}</div>", n);
                        totalMatch++;
                    }
                    else if (n == this.ResultBonusBall)
                    {
                        builder.AppendFormat("<div class=\"bonus-match\">{0}</div>", n);
                        bonusMatch = true;
                    }
                    else
                    { 
                        builder.AppendFormat("<div class=\"no-match\">{0}</div>", n);
                    //}



                }

                //if (totalMatch >= 5 && bonusMatch)
                //    totalMatch++;

                builder.Append("</div>");
                //builder.AppendFormat("<div class=\"result\">{0}</div>", totalMatch);

                return builder.ToString();

            }
            else
            {
*/
            StringBuilder builder = new StringBuilder();

            builder.Append("<div class=\"numbers\">");
            foreach (int n in a)
            {
                builder.AppendFormat("<div class=\"no-match\">{0}</div>", n);
            }
            builder.Append("</div>");

            return builder.ToString();
            // }

        }

        public string PrintLinesRemaining()
        {
            return this.RemainingFunds.ToString();

        }

        #endregion

        protected void ButtonAdd_Click(object sender, EventArgs e)
        {
            bool actionPeformed = false;



            ControlCollection repeaterRows = this.FindControl("RepeaterList").Controls;
            HtmlInputCheckBox cb;

            int remaining = this.RemainingFunds;

            int minimumFunds = 1;
            if (this.CurrentDraw.type == draw.drawType.EUROMILLIONS)
                minimumFunds = 2;

            if ((int)CurrentDraw.pricePerLine != 0)
            {
                minimumFunds = (int) CurrentDraw.pricePerLine;
            }

            foreach (Control row in repeaterRows)
            {
                cb = (System.Web.UI.HtmlControls.HtmlInputCheckBox)row.FindControl("chkAction");
                if (cb.Checked && remaining >= minimumFunds)
                {
                    int? ObjectId = Utilities.StringToInt(cb.Value.Replace("lineId_", ""));

                    if (ObjectId.HasValue)
                    {
                        line l = this.BasePage.BusinessFacade.LineBL.GetSingle(ObjectId.Value);

                        if (l != null)
                        {


                            int counter = this.BasePage.BusinessFacade.LineBL.SelectAllByDrawIdAndNumbers(this.CurrentDraw.id, l.numbers).Count();
                            if (counter == 0)
                            {
                                line newl = new line();


                                newl.drawId = this.CurrentDraw.id;
                                newl.numbers = l.numbers;

                                
                                if (this.BasePage.BusinessFacade.LineBL.InsertLine(newl))
                                {
                                    InsertEventLogEntry("Line [" + newl.id.ToString() + "] added.");

                                    remaining--;
                                    if (!actionPeformed)
                                        actionPeformed = true;
                                }
                            }
                        }
                    }
                }

            }

            if (actionPeformed)
            {

                this.BasePage.Redirect(String.Format("/Secured/Draws/?dId={0}&Tab=2", this.DrawId));
            }
        }
    }
}